package com.example.treehole;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.treehole.activity.BaseActivity;
import com.example.treehole.activity.MainActivity;
import com.example.treehole.activity.RegisterActivity;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.LoginResponse;
import com.example.treehole.utils.CountDownTimerUtils;
import com.example.treehole.utils.StatusBarUtil;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;


public class LoginActivity extends BaseActivity {


    @BindView(R.id.et_account_one)
    EditText etAccountOne;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_login_one)
    Button btnLoginOne;
    @BindView(R.id.ll_login_one)
    LinearLayout llLoginOne;
    @BindView(R.id.et_account_two)
    EditText etAccountTwo;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.btn_login_two)
    ImageButton btnLoginTwo;
    @BindView(R.id.ll_login_two)
    LinearLayout llLoginTwo;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_change)
    TextView tvChange;

    private String account, password, code;
    private int LOGIN_TYPE = 1;  //登录方式 1为验证码登录 2为密码登录
    private LoadingDialog loadingDialog;

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {
        String s=getStringFromSp("isLogin");
        //检查是否登录
        if (!TextUtils.isEmpty(getStringFromSp("isLogin")) && !getStringFromSp("isLogin").equals("false")){
            jumpTo(MainActivity.class);
            return;
        }
        //设置导航栏颜色
        StatusBarUtil.setTranslucentForCoordinatorLayout(this, 0);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==1){
                //开始倒计时
                CountDownTimerUtils countDownTimerUtils=new CountDownTimerUtils(tvGetCode,60000,1000);
                countDownTimerUtils.start();
            }else if (msg.what==2){
                loadingDialog.close();
            }
        }
    };

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.btn_login_one, R.id.tv_get_code, R.id.btn_login_two, R.id.tv_register, R.id.tv_change})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login_one:
            case R.id.btn_login_two:
                if (isValid())
                    login();
                break;
            case R.id.tv_get_code:
                getCode();
                break;
            case R.id.tv_register:
                jumpTo(RegisterActivity.class);
                break;
            case R.id.tv_change:
                if (LOGIN_TYPE == 1) {
                    tvChange.setText(getString(R.string.code_login));
                    llLoginOne.setVisibility(View.GONE);
                    llLoginTwo.setVisibility(View.VISIBLE);
                    LOGIN_TYPE = 2;
                } else {
                    tvChange.setText(getString(R.string.pass_login));
                    llLoginTwo.setVisibility(View.GONE);
                    llLoginOne.setVisibility(View.VISIBLE);
                    LOGIN_TYPE = 1;
                }
                break;
        }
    }


    private boolean isValid() {
        if (LOGIN_TYPE == 1) {
            account = etAccountOne.getText().toString();
            code = etCode.getText().toString();
            if (TextUtils.isEmpty(account)) {
                showToast(getString(R.string.input_account));
                return false;
            }
            if (TextUtils.isEmpty(code)) {
                showToast(getString(R.string.input_password));
                return false;
            }
        } else {
            account = etAccountTwo.getText().toString();
            password = etPassword.getText().toString();
            if (TextUtils.isEmpty(account)) {
                showToast(getString(R.string.input_account));
                return false;
            }
            if (TextUtils.isEmpty(password)) {
                showToast(getString(R.string.input_password));
                return false;
            }
        }
        return true;
    }

    private void getCode() {
        String account=etAccountOne.getText().toString();
        if (TextUtils.isEmpty(account)){
            showToast(getString(R.string.input_account));
            return;
        }
        HashMap<String,String> mParams=new HashMap<>();
        mParams.put("username",account);
        Api.config(ApiConfig.GET_CODE_URL,mParams).getRequest(this,new Callback() {
            @Override
            public void onSuccess(String res) {
                Log.d("res:",res);
                //发送完验证码，直接由服务端验证
                mHandler.sendEmptyMessage(1);
                showToastSync(getString(R.string.publish_code));
            }
            @Override
            public void onFailure(Exception e) {
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    private void login() {
        String url="";
        HashMap<String,String> mParams=new HashMap<>();
        mParams.put("username",account);
        if (LOGIN_TYPE==1){
            url=ApiConfig.LOGIN_CODE_URL;
            mParams.put("code",code);
        }else{
            url=ApiConfig.LOGIN_PASS_URL;
            mParams.put("password",password);
        }
        loadingDialog=new LoadingDialog(this);
        loadingDialog.setLoadingText("登录中").show();
        Api.config(url, mParams).postRequest(this,new Callback() {
            @Override
            public void onSuccess(String res) {
                try {
                    LoginResponse loginResponse = new Gson().fromJson(res, LoginResponse.class);
                    if (loginResponse.getCode().equals("200")) {
                        //保存一些信息
                        saveStringToSp("token", loginResponse.getToken());
                        saveStringToSp("account", account);
                        saveStringToSp("id", loginResponse.getId());
                        saveStringToSp("isLogin", "true");
                        mHandler.sendEmptyMessage(2);
                        jumpTo(MainActivity.class);
                        showToastSync(getString(R.string.login_success));
                        finish();
                    } else {
                        mHandler.sendEmptyMessage(2);
                        showToastSync(loginResponse.getMsg());
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    showToastSync(getString(R.string.parsing_failure));
                }
            }
            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}